package byteMath

import (
	"encoding/binary"
	"fmt"
	"log"
	"strconv"
)

func Byte2Str(b byte, targetBase int, tarBit int) (string, error) {
	parseInt, err := strconv.ParseInt(fmt.Sprintf("%d", b), 10, 64)
	if err != nil {
		return "", err
	}
	rs := strconv.FormatInt(parseInt, targetBase)
	for len(rs) < tarBit {
		rs = "0" + rs
	}
	return rs, nil
}

func Str2Byte(str string, originBase int) (byte, error) {
	parseInt, err := strconv.ParseInt(str, originBase, 64)
	if err != nil {
		return 0, err
	}
	return uint8(parseInt), nil
}

func Int2Str(i int, targetBase int, tarBit int) (string, error) {
	parseInt, err := strconv.ParseInt(fmt.Sprintf("%d", i), 10, 64)
	if err != nil {
		return "", err
	}
	str := strconv.FormatInt(parseInt, targetBase)
	for len(str) < tarBit {
		str = "0" + str
	}
	return str, nil
}

func Str2Int(str string, originBase int) (int, error) {
	parseInt, err := strconv.ParseInt(str, originBase, 64)
	if err != nil {
		return 0, err
	}
	return int(parseInt), nil
}

func ByteArr2Int(b []byte) (int, error) {
	str := ""
	for i := range b {
		tmp, err := Byte2Str(b[i], 16, 2)
		if err != nil {
			return 0, err
		}
		str = str + tmp
	}
	return Str2Int(str, 16)
}

func Int2ByteArr(i int, tarBit int) (res []byte, success bool) {
	if tarBit > 8 {
		return nil, false
	}
	success = false
	defer func() {
		err := recover()
		if err != nil {
			log.Println(err)
		}
	}()
	buf := make([]byte, 8)
	binary.BigEndian.PutUint64(buf, uint64(i))
	buf = buf[8-tarBit:]
	return buf, true
}
